/**
 * Created by charsen on 16/5/27.
 */
directives.directive('moveable', ["$rootScope", "tools", "$timeout", "$document", function ($rootScope, tools, $timeout, $document) {
    return {
        restrict: 'A',
        scope: false,
        link: function (scope, element, attr) {
            var left = 0, top = 0, moveX = 0, moveY = 0, pageX = 0, pageY = 0;
            var $container = $('.charts-container'), $ele = $(element), width = $container.width();
            scope.moving = false;

            element.on('mousedown', function (event) {
                if (scope.resizing || scope.previewing) {
                    return;
                }

                pageX = event.pageX;
                pageY = event.pageY;

                top = $ele.position().top;
                left = $ele.position().left;

                $document.on('mousemove', mousemove);
                $document.on('mouseup', mouseup);
            });

            function mousemove (event) {
                if (scope.resizing || scope.previewing || !scope.selected) {
                    return;
                }

                moveX = event.pageX - pageX;
                moveY = event.pageY - pageY;

                pageX = event.pageX;
                pageY = event.pageY;

                left += moveX;
                top += moveY;

                if (left < 3 || top < 3 || left > width - $ele.width() - 5) {
                    return;
                }

                $ele.css({
                    left: left + 'px',
                    top: top + 'px'
                });

                if ($ele.position().top + $ele.height() > $container.height() - 50) {
                    borderExpand();
                }

                scope.moving = true;

                // 绘制辅助线
                scope.drawAuxiliaryLine(true, $ele);
            }

            function mouseup () {
                $document.off('mousemove', mousemove);
                $document.off('mouseup', mouseup);

                $timeout(function () {
                    scope.moving = false;
                }, 50);

                // 绘制辅助线
                scope.drawAuxiliaryLine(false);

                // 寻找合适的方块
                findSquare();
            }

            function borderExpand () {
                $container.height($container.height() + 100);
            }

            function findSquare () {
                var square = $rootScope.getMatchedSquare(left, top);
                if (square) {
                    $ele.css({
                        left: square.left,
                        top: square.top
                    });

                    square.used = true;
                }
            }
        }
    }
}]);